/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import ejb.SponsorUserManager;
import ejb.SponsoredEvent;
import ejb.SponsoredEventManager;
import facebook.Utilities;
import fql.FqlEvent;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Stefano
 */
@WebServlet(name = "SponsoredEventManagerServlet", urlPatterns = {"/SponsoredEventManagerServlet"})
public class SponsoredEventManagerServlet extends HttpServlet {

    @EJB
    private SponsorUserManager sponsorUserManager;
    @EJB
    private SponsoredEventManager sponsoredEventManager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Calendar cal = Calendar.getInstance();
        Date time = cal.getTime();


        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        if (session.getAttribute("userid") != null) {


            String credit, accessToken, userId;

            userId = session.getAttribute("userid").toString();
            accessToken = session.getAttribute("token").toString();

            //controllare che la sessione non sia null!!!

            FacebookClient facebookClient = new DefaultFacebookClient(accessToken);

            List<String> alreadyInsertEid = new LinkedList<String>();
            List<FqlEvent> possibleToInsert = new LinkedList<FqlEvent>();
            List<FqlEvent> toInsert = new LinkedList<FqlEvent>();

            List<SponsoredEvent> alreadyInsert = new LinkedList<SponsoredEvent>();

            String queryToInsert = null;

            //lista di eid gia sponsorizzati dall utente userId
            alreadyInsert = sponsoredEventManager.getEventUser(userId);
            //System.err.println("DEBUG: "+alreadyInsert);
            alreadyInsertEid = sponsoredEventManager.findSposoredEventUid(userId);

            queryToInsert = "SELECT creator, eid, name, location, venue FROM event WHERE eid IN "
                    + "(SELECT eid FROM event_member WHERE uid=" + userId + ") AND creator =" + userId + "";

            queryToInsert += " AND (start_time >= " + (time.getTime() / (1000)) + ") ";

            possibleToInsert = facebookClient.executeQuery(queryToInsert, FqlEvent.class);


            //in toInsert metto solo gli eventi che non sono gia stati sponsorizzati
            for (FqlEvent fqle : possibleToInsert) {
                if (!alreadyInsertEid.contains(fqle.getEid())) {

                    toInsert.add(fqle);
                }
            }

            if (sponsorUserManager.isNewSponsorUser(userId)) {
                sponsorUserManager.addSponsorUser(userId, 0);
            }

            credit = String.valueOf(sponsorUserManager.findSponsorUser(userId).getCredit());



            request.setAttribute("credit", credit);
            request.setAttribute("alreadyInsert", alreadyInsert);
            request.setAttribute("toInsert", toInsert);
            ServletContext sc = getServletContext();
            RequestDispatcher rd = sc.getRequestDispatcher("/SponsoredEventManager.jsp");
            rd.forward(request, response);

        } else {
            response.sendRedirect(Utilities.getBaseUrl(request));
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
